<template>
  <div class="select-record">
    <div class="model-title">2、选择养护记录</div>
    <div class="handle-btn">
        <BaseButton style="margin: 10px" @click="handleDialogShow">选择养护记录</BaseButton>
        <BaseButton style="margin: 10px" type="second" :disabled="!selectLength" @click="batchDelete">批量移除</BaseButton>
        <BaseButton v-permission="{ btnCode: 'dlyh_d416_e20_2' }" style="margin: 10px" type="second" :disabled="!selectLength" @click="exportVisaCard">导出签证单</BaseButton>
        <BaseButton v-permission="{ btnCode: 'dlyh_d416_e21_2' }" style="margin: 10px" type="second" :disabled="!selectLength" @click="exportFileCard">导出档案卡</BaseButton>
    </div>
    <div class="tips">
        <i class="el-icon-info info-icon"></i>
        <span>已选择
            <span class="num">{{ selectLength }}</span>
            条养护记录
            <span v-if="startDateAndEndDate[0]">
                ，养护日期范围：{{ startDateAndEndDate[0] }} ~{{ startDateAndEndDate[1] }}
            </span>
        </span>
    </div>
    <div v-if="showError" class="error-message">请选择养护记录</div>
    <div class="table-warp">
        <!-- 全选 -->
        <div class="check-all">
            <el-checkbox v-model="checked" @change="checkAll"></el-checkbox>
        </div>
        <BaseTable 
        slot="table"
        ref="table" 
        class="table"  
        :data="pageList" 
        :columns="columns"
        highlight-current-row 
        height="calc(100% - 73px)" 
        @sort-change="handleSortChange"
        >
            <template #code="{ scope: { row} }">
               <BaseButton type="text" @click="handleDetail(row)">  {{ row.recordCode }}</BaseButton>
            </template>
            <template #select="{ scope: { row} }">
                <el-checkbox v-model="row.checked"></el-checkbox>
            </template>
            <template #type="{ scope: { row} }">
                {{ row.type | value2Name(types) }}
            </template>
            <template #msStatus="{ scope: { row} }">
                <StateTag  :id="row.msStatus" type="jiliang"></StateTag>
            </template>
            <template #action="{ scope: { row} }">
                <BaseButton type="text" color="danger" @click="handleDelete(row)">删除</BaseButton>
            </template>
        </BaseTable>
        <Pagination
            clas="pagination"
            :current-page.sync="page.pageNo"
            :page-size.sync="page.pageSize"
            :total="page.total"
            @size-change="classPageList"
            @current-change="classPageList"
        />
    </div>
    <!-- 养护记录选择弹框 -->
    <SelectDialog ref="select-dialog" :del-dev-in-detail="delDevInDetail" :query-data="query" @selectChange="handleSelectChange"></SelectDialog>
    <div class="btn">
      <BaseButton type="second" @click="handleBack">上一步</BaseButton>
      <BaseButton @click="handleNext">保存并下一步</BaseButton>
    </div>
  </div>
</template>
<script>
import { MetrologicalStatusOptions } from '@/views/maintenance-decision/constants'
import { value2Name } from '@/filters'
import StateTag from '../components/StateTag.vue'
import { ApplicationModel, MsMaintrecordModel } from '@/models'
import SelectDialog from '../components/SelectDialog.vue'
// 导出
import { ApplicationApi } from '@/api'
import downLoad from '@/utils/blob-download'
export default {
    components: {
        StateTag,
        SelectDialog
    },
    filters: {
        value2Name
    },
    props: {
        form: {
            type: Object,
            default: () => {}
        },
        curStep: {
            type: [Number],
            required: false,
            default: 1
        },
        pageType: {
            type: String,
            required: true,
        }
    },
    data() {
        return {
            model: new ApplicationModel(),
            msMaintrecordModel: new MsMaintrecordModel(),
            page: {
                pageNo: 1,
                pageSize: 10,
                total: 0
            },
            list: [], // 全量list
            pageList: [], // 当前页面的list
            columns: [
                {
                   
                    slot: 'select',
                    attrs: {
                        label: '',
                        prop: 'cehcked',
                        aling: 'left',
                        width: 60,
                    }
                },
                {
                    slot: 'code',
                    attrs: {
                        label: '养护记录编号',
                        prop: 'code',
                        width: 150,
                    }
                },
                {
                    attrs: {
                        label: '养护日期',
                        prop: 'maintDate',
                        'show-overflow-tooltip': true,
                        sortable: 'custom',
                    }
                },
                {
                    slot: 'type',
                    attrs: {
                        label: '类型',
                        prop: 'type',
                        'show-overflow-tooltip': true,
                        // width: 100
                    }
                },
                {
                    attrs: {
                        label: '施工单位',
                        prop: 'constructionUnitName',
                        'show-overflow-tooltip': true
                    }
                },
                
                {
                    attrs: {
                        label: '现场管理',
                        prop: 'managementUnitName',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '工作内容',
                        prop: 'workContent',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'msStatus',
                    attrs: {
                        label: '计量状态',
                        prop: 'msStatus',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '更新人',
                        prop: 'operatorName',
                    }
                },
                {
                    attrs: {
                        label: '更新时间',
                        prop: 'updateTime',
                        sortable: 'custom',
                    }
                },
                {
                    slot: 'action',
                    attrs: {
                        label: '操作',
                        width: '100',
                    }
                }
            ],
            metrologicalStatusOptions: MetrologicalStatusOptions, // 计量状态
            query: {
                msStatusList: [1],
                cycle: '',
                typeList: [],
                startDate: '',
                endDate: '',
                constructionUnitId: ''
            },
            firstSetDefualt: true, // 是否是初次拉取默认列表
            checked: false, // 是否全选
            selectList: [], // 编辑时已选的设备
            showError: false, // 显示设备未选错误提示
        }
    },   
    computed: {
        // 页码数组
        pageArr() {
            const num = Math.ceil(this.list.length / this.page.pageSize)
            const arr = []
            for (let i = 1; i <= num; i++) {
                arr.push(i)
            }
            return arr
        },
        types() {
            return this.$store.state.types.maintenanceApplyTypes || []
        },
        selectLength() {
            return this.list.filter(el => el.checked).map(el => el.id).length || 0
        },
        startDateAndEndDate() {
            const dateList = this.list.filter(el => el.checked).map(el => el.maintDate)
            let start = ''
            let end = ''
            if (dateList.length && dateList.length === 1) {
                start = dateList[0]
                end = dateList[0]
            } else if (dateList.length && dateList.length >= 2) {
                const {minDate, maxDate} = this.findMinAndMaxDates(dateList)
                start = minDate
                end = maxDate
            } else {
                start = ''
                end = ''
            }
            return [start, end]
        },
        // 详情里被删除的设备
        delDevInDetail() {
            const devArr = []
            const listIds = this.list.map(el => el.id)
            this.selectList.forEach(el => {
                if (listIds.indexOf(el.id) === -1) {
                    devArr.push(el)
                }
            })
            // console.log('dev', devArr)
            return devArr 
        }
    },
    watch: {
        form: {
            immediate: true,
            deep: true,
            handler(val) {
                this.query.cycle = this.form.cycle
                this.query.typeList = [this.form.type]
                this.query.constructionUnitId = this.form.contractorId // 申请单位的ID
                this.query.startDate = this.$dayjs(this.form.cycle).startOf('month').format('YYYY-MM-DD')
                this.query.endDate = this.$dayjs(this.form.cycle).endOf('month').format('YYYY-MM-DD')
                this.query.highwayCode = this.form.highwayCode // 高速
                this.query.contractId = this.form.contractId
                if (this.firstSetDefualt && this.curStep === 1) {
                    this.getDefualtList()
                }
            }
        },
        // 设备未选提示信息不显示
        list: {
            immediate: true,
            deep: true,
            handler(val) {
                if (val.length) {
                    this.showError = false
                }
                this.page.total = this.list.length
            }
        },
        selectLength: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.showError = false
                }
            }
        },

    },
    created() {
        this.getTypes()
    },
    methods: {
        // 查看养护记录详情查看养护记录详情
        handleDetail(row) {
            const targetUrl = this.$router.resolve({
                name: 'MaintenanceRecordManagementDetail',
                query: {
                    id: row.id,
                }
            }).href
            // 使用window.open在新标签页中打开该URL
            window.open(targetUrl, '_blank')
        },
        findMinAndMaxDates(dates) {
            let minDate = new Date(dates[0])
            let maxDate = new Date(dates[0])
 
            for (let i = 1; i < dates.length; i++) {
                const date = new Date(dates[i])
                if (date < minDate) {
                    minDate = date
                } else if (date > maxDate) {
                    maxDate = date
                }
            }
 
            return { 
                minDate: this.$dayjs(minDate).format('YYYY-MM-DD'), 
                maxDate: this.$dayjs(maxDate).format('YYYY-MM-DD')
            }
        },
        getTypes() {
            this.$store.dispatch('types/query', 'maintenanceApplyTypes')
        },
        // 上一步
        handleBack() {
            this.$emit('back', this.form)
        },
        // 下一步
        handleNext() {
            if (!this.selectLength) {
                this.showError = true // 如果没有勾选的话默认勾选所有
                return
            }
            const ids = this.list.filter(el => el.checked).map(el => el.id)
            const data = {
                ...this.form,
                maintRecordIdList: ids

            }
            this.model.applySave({...data}).then(res => {
                this.form.id = res.id
                this.$emit('next', res)
                this.selectIds = []
            })
        },
        // 分页操作
        classPageList() {
            const pageSize = this.page.pageSize
            this.pageList = []
            const pageNo = this.page.pageNo
            const endIndext = pageNo * pageSize // 10  slice函数左闭右开
            const startIndex = endIndext - 1 - (pageSize - 1) // 0
            const list = [...this.list]
            this.pageList = list.slice(startIndex, endIndext)
        },
        // 排序, ascending升序 descending降序
        handleSortChange({ column, prop, order }) {  
            if (prop === 'updateTime') {
                if (order === 'ascending') {  
                    this.sortList('updateTime', 'ascending')
                    this.classPageList()
                } else {
                    // 默认排序
                    this.sortList('updateTime', 'descending')
                    this.classPageList()
                }
            }
            if (prop === 'maintDate') {
                if (order === 'ascending') {  
                    this.sortList('maintDate', 'ascending')
                    this.classPageList()
                } else {
                    this.sortList('maintDate', 'descending')
                    this.classPageList()
                }
            }
        },
        sortList(key, order) {
            this.list.sort(function(a, b) {
                var keyA = new Date(a[key])
                var keyB = new Date(b[key])
                // 正序排序
                if (order === 'ascending') {
                    if (keyA > keyB) return 1
                    if (keyA < keyB) return -1
                } else if (order === 'descending') {
                    if (keyA > keyB) return -1
                    if (keyA < keyB) return 1
                } else {
                    return 0
                }
                return 0
            })
        },
        // 选择弹框
        handleDialogShow() {
            console.log('delDevInDetail', this.delDevInDetail)
            this.$refs['select-dialog'].listIds = this.list.map(el => el.id)
            this.$refs['select-dialog'].visible = true
        },
        getDefualtList() {
            this.msMaintrecordModel.getList({...this.query}).then(res => {
                if (res) {
                    // 新增
                    if (this.pageType === 'add') {
                        this.list = [...res].map(el => {
                            return {
                                ...el,
                                checked: false
                            }
                        })
                    } else {
                        // 编辑
                        const selectList = this.selectList.map(el => {
                            return {
                                ...el,
                                checked: true
                            }
                        })
                        const list = [...res].map(el => {
                            return {
                                ...el,
                                checked: false
                            }
                        })
                        this.list = selectList.concat(list)
                    }
                    
                    this.firstSetDefualt = false
                    this.classPageList()
                }
            }
            )
        },
        // 全选
        checkAll(val) {
            this.list = this.list.map(el => {
                return {
                    ...el,
                    checked: val
                }
            })
            this.classPageList()
        },
        // 删除
        handleDelete(row) {
            this.list = this.list.filter(el => el.id !== row.id)
            this.classPageList()
        },
        // 选择记录并关闭弹框
        handleSelectChange(list) {
            this.list = this.list.concat(list)
            this.classPageList()
        },
        // 批量移除
        batchDelete() {
            this.list = [...this.list].filter(el => !el.checked)
            this.classPageList()
        },
        // 导出签证卡
        exportVisaCard() {
            let ids = this.list.filter(el => el.checked).map(el => el.id)
            if (!ids.length) {
                ids = this.list.map(el => el.id)
            }

            // 操作
            this.exportLoading = true
            const path = ApplicationApi.qzdPath
            const params = {
                ids,
                type: this.form.type, // 类型
                msStatuses: [1, 3], // 计量状态
                contractId: this.form.contractId, // 所属合同
                highwayCode: this.form.highwayCode, // 高速
                startDate: this.startDateAndEndDate[0], // 养护开始时间
                endDate: this.startDateAndEndDate[1] // 养护结束时间
            }
            downLoad(path, {...params}, '', 'Excel', () => {
                this.exportLoading = false
            })
        },
        // 导出档案卡
        exportFileCard() {
            let ids = this.list.filter(el => el.checked).map(el => el.id)
            if (!ids.length) {
                ids = this.list.map(el => el.id)
            }
            // 操作
            this.exportLoading = true
            const path = ApplicationApi.dakPath
            const params = {
                ids,
                type: this.form.type, // 类型
                msStatuses: [1, 3], // 计量状态
                contractId: this.form.contractId, // 所属合同
                highwayCode: this.form.highwayCode, // 高速
                startDate: this.startDateAndEndDate[0], // 养护开始时间
                endDate: this.startDateAndEndDate[1] // 养护结束时间
            }
            downLoad(path, {...params}, '', 'Excel', () => {
                this.exportLoading = false
            })
        }
    }
}
</script>
<style scoped lang="scss">
.select-record{
  height:  calc(100% - 90px);
  width: 100%;
  margin-top: 24px;
  box-shadow: 0px 0px 4px 0px rgba(131, 145, 178, 0.2);
  position: relative;
  .handle-btn{
    display: flex;
  }
  .tips{
    margin:8px;
    background-color:rgba(4, 97, 255, 0.1) ;
    border: 1px solid rgba(4, 97, 255, 0.2);
    padding: 10px ;
    border-radius: 4px;
    font-size:14px;
    .num,.info-icon{
        color: #409EFF;
        margin-right: 8px;
    }
  }
  .error-message{
    color: red;
    font-size:14px;
    padding: 10px;
    border-radius: 4px;
    background-color:rgba(255, 4, 4, 0.1) ;
    border: 1px solid rgba(255, 4, 4, 0.2);
    margin:8px;
  }
  .table-warp{
    width:100%;
    height: 70%;
    position: relative;
    .table{
        width:100%;
    }
    .check-all{
        width:60px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        margin-top: 14px;
    }
    .pagination{
        position: absolute;
        right: 24px;
        bottom: 16px;
    }
  }
 
  .model-title{
    width: 100%;
    padding: 16px 24px;
    border-bottom: 1px solid rgba(131, 145, 178, 0.1);
  }
  .btn{
    width: 100%;
    display: flex;
    justify-content: center;
    position: absolute;
    bottom: 24px;
  }
}

</style>
